package com.china.zhuoyue.api.login

import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.china.zhuoyue.api.core.*
import com.china.zhuoyue.api.core.ConvertInterceptor.Companion.JSON_CONTENT_TYPE_HEADER
import kotlinx.coroutines.Job
import retrofit2.http.*

val LOGIN_API_SERVICE: LoginApiService get() = ApiHelper.create(LoginApiService::class.java)
fun <T> ComponentActivity.launchUILogin(
    block: suspend LoginApiService.() -> T,
    apiObserver: Observer<ApiProcess<T>>? = null,
    error: ApiError? = null,
    complete: ApiComplete? = null
): Job = ApiRequest(lifecycleScope, LOGIN_API_SERVICE).launchUI(block, error, complete, apiObserver)

fun <T> Fragment.launchUILogin(
    block: suspend LoginApiService.() -> T,
    apiObserver: Observer<ApiProcess<T>>? = null,
    error: ApiError? = null,
    complete: ApiComplete? = null,
): Job = ApiRequest(lifecycleScope, LOGIN_API_SERVICE).launchUI(block, error, complete, apiObserver)

fun <T> ViewModel.launchUILogin(
    block: suspend LoginApiService.() -> T,
    apiObserver: Observer<ApiProcess<T>>? = null,
    error: ApiError? = null,
    complete: ApiComplete? = null
): Job = ApiRequest(viewModelScope, LOGIN_API_SERVICE).launchUI(block, error, complete, apiObserver)

interface LoginApiService {

    /**
     * 发送短信
     * 注册，找回密码，验证
     * 001 002  003
     */
    @POST("/api/send_sms")
    @Headers(JSON_CONTENT_TYPE_HEADER)
    @FormUrlEncoded
    suspend fun sendSms(
        @Field("mobile") mobile: String,
        @Field("type") type: String,
    ): String?

    /**
     * 发送短信
     * 注册，找回密码，验证
     * 001 002  003
     */
    @GET("/api/app/version/info")
    suspend fun version(@Query("type") type: Int = 1): Version?

    /**
     * 密码登录
     */
    @POST("/api/login")
    @Headers(JSON_CONTENT_TYPE_HEADER)
    @FormUrlEncoded
    suspend fun login(
        @Field("mobile") mobile: String,
        @Field("password") password: String = "",
    ): UserInfoBean?

    /**
     * 注册
     */
    @POST("/api/register")
    @Headers(JSON_CONTENT_TYPE_HEADER)
    @FormUrlEncoded
    suspend fun register(
        @Field("mobile") mobile: String,
        @Field("password") password: String = "",
        @Field("vcode") vcode: String = "",
    ): UserInfoBean?

    /**
     * 手机+验证码
     */
    @POST("/customer/api/forgetPassword/reset")
    suspend fun forgetPassword(
        @Query("mobile") mobile: String,
        @Query("newPassword") newPassword: String,
        @Query("code") code: String,
    ): UserInfoBean?


}